package handler

import (
	"github.com/gin-gonic/gin"
	"mock-exam2/cache"
	"mock-exam2/model"
	"mock-exam2/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名和密码不能为空",
		})
		return
	}
	var user model.User
	redis_key := "user_error_" + "username"
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账户已被封禁",
		})
		return
	}
	if err := model.DB.Where("username = ?", username).Limit(1).Find(&user).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户信息查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if pkg.Md5(user.Password) != password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次,封禁1小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"user": user,
	})
	return
}
func RoleAddNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	roleNode := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	if rid == 0 || nid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "角色id和权限id不可为空",
		})
		return
	}
	model.DB.Create(&roleNode)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "角色权限添加成功",
	})
	return
}
func UserDetail(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	var userRole model.UserRole
	model.DB.
		Where("user_roles.uid = ?", uid).
		Limit(1).
		Find(&userRole)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": userRole,
	})
	return
}
func RoleDetail(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	var roleNode model.RoleNode
	model.DB.
		Where("role_nodes.rid = ?", rid).
		Limit(1).
		Find(&roleNode)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": roleNode,
	})
	return
}
